package com.example.music_liwei.interceptor;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MyInterceptor implements Interceptor {
    private final String TAG = "ning";

    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {

        Request request = chain.request();

        //-- 添加公共请求头

        Request.Builder requestBuilder =request.newBuilder();

        //添加请求头信息
        requestBuilder.addHeader("userId","userId");
        requestBuilder.addHeader("token","token");
        requestBuilder.addHeader("versionCode","120");
        requestBuilder.addHeader("versionName","1.2.0");

        //get 接口添加公共函数
        if(TextUtils.equals(request.method(), "GET"))
        {
            HttpUrl.Builder httpUrlBuilder = request.url().newBuilder();
            httpUrlBuilder.addQueryParameter("userId","userId");
            httpUrlBuilder.addQueryParameter("token","token");

            requestBuilder.url(httpUrlBuilder.build());
        }


        //--  --    -   --  -   -   --  -   -

        Log.i(TAG, "intercept:request信息 " + request.toString());

        String method = request.method();
        if (TextUtils.equals(method, "GET")) {
            RequestBody body = request.body();
            if (body != null)
                Log.i(TAG, "intercept: body 信息" + body.toString());
            else
                Log.i(TAG, "intercept: body 信息为空" );

        }
        Response response = chain.proceed(request);
        int code = response.code();
        ResponseBody body = response.body();
        Log.i(TAG, "intercept: response 信息 code:" + code);

        if (body != null) {
            // body只能读取一次
            String bodyStr = body.string();
            Log.i(TAG, "intercept: response信息:body" + bodyStr);
            MediaType mediaType = body.contentType();
            return response.newBuilder().body(ResponseBody.create(mediaType, bodyStr)).build();

        }

        //return response;
        // 公共请求头
        return chain.proceed(requestBuilder.build());
    }


    public String bodyToString(RequestBody body) {
        // 检查请求体是否为null
        if (body != null) {
            return body.toString();
        } else {
            return "";
        }
    }
}